package cn.stylefeng.guns.modular.rest.hxStoragePut;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.stylefeng.guns.modular.hx.basic.entity.HxBasicGoods;
import cn.stylefeng.guns.modular.hx.basic.service.HxBasicGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.hx.storage.entity.HxStoragePutDetailed;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStoragePutDetailedParam;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStoragePutParam;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStorageStockParam;
import cn.stylefeng.guns.modular.hx.storage.model.result.HxStoragePutDetailedResult;
import cn.stylefeng.guns.modular.hx.storage.model.result.HxStoragePutResult;
import cn.stylefeng.guns.modular.hx.storage.model.result.HxStorageStockResult;
import cn.stylefeng.guns.modular.hx.storage.service.HxStoragePutDetailedService;
import cn.stylefeng.guns.modular.hx.storage.service.HxStoragePutService;
import cn.stylefeng.guns.modular.rest.aop.UserAop;
import cn.stylefeng.guns.sys.modular.system.entity.Menu;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;

/**
 * 零售  入库
 * @author zcx
 *
 */
@Controller
@RequestMapping("/rest/HxStoragePut")
public class restHxStoragePutController extends BaseController {

    @Autowired
    private UserAop userAop;

    @Autowired
    private HxStoragePutService hxStoragePutService;

    @Autowired
    private HxStoragePutDetailedService hxStoragePutDetailedService;
    @Autowired
    private HxBasicGoodsService hxBasicGoodsService;
    /**
     * 入库单列表
     * 查询入库单列表
     */
    @ResponseBody
    @RequestMapping("/storagelist")
    public ResponseData storagelist(HxStoragePutParam hxStoragePutParam) {
		User user = userAop.getUser();
		hxStoragePutParam.setStorageState("未完成");
		hxStoragePutParam.setDeptId(user.getDeptId());
		hxStoragePutParam.setOperateId(user.getOperateId());
		List<HxStoragePutResult> list = hxStoragePutService.restfindstoragelist(hxStoragePutParam);
        return ResponseData.success(list);
    }
    
    /**
     * 入库单
     * 查询入库单
     */
    @ResponseBody
    @RequestMapping("/storage")
    public ResponseData storage(HxStoragePutParam hxStoragePutParam) {
		HxStoragePutResult res = hxStoragePutService.restfindstorage(hxStoragePutParam);
        return ResponseData.success(res);
    }
    
    /**
     * 入库单商品列表
     * 查询入库单商品列表
     */
    @ResponseBody
    @RequestMapping("/detailedSumlist")
    public ResponseData detailedSumlist(HxStoragePutDetailedParam hxStoragePutDetailedParam) {
    	List<HxStoragePutDetailedResult> res = hxStoragePutDetailedService.restfinddetailedSumlist(hxStoragePutDetailedParam);
        return ResponseData.success(res);
    }
    
    /**
     * 入库单商品
     * 查询入库单商品
     */
    @ResponseBody
    @RequestMapping("/detailedSum")
    public ResponseData detailedSum(HxStoragePutDetailedParam hxStoragePutDetailedParam) {
    	HxStoragePutDetailedResult res = hxStoragePutDetailedService.restfinddetailedSum(hxStoragePutDetailedParam);
        res.setBoxNumStr("-");
    	StringBuffer boxNumStr = new StringBuffer();
    	if(ToolUtil.isNotEmpty(res.getGoodsId())){
            HxBasicGoods hxBasicGoods = this.hxBasicGoodsService.getById(res.getGoodsId());
            if(ToolUtil.isNotEmpty(hxBasicGoods) && ToolUtil.isNotEmpty(hxBasicGoods.getBoxSpecs())){
                    try {
                        res.setBoxSpecs(hxBasicGoods.getBoxSpecs());
                        BigDecimal boxSpecs = new BigDecimal(hxBasicGoods.getBoxSpecs());
                    if(ToolUtil.isNotEmpty(res.getNum())){
                        BigDecimal zs = new BigDecimal(res.getNum()).divide(boxSpecs, 0, RoundingMode.DOWN);
                        if(zs.compareTo(BigDecimal.ZERO) > 0){
                            boxNumStr.append(zs).append("箱");
                        }
                        BigDecimal ys = new BigDecimal(res.getNum()).remainder(boxSpecs);
                        if(ys.compareTo(BigDecimal.ZERO) > 0){
                            boxNumStr.append(ys.setScale(0,BigDecimal.ROUND_UP)).append(hxBasicGoods.getJibenUnit());
                        }
                    }
                    if(boxNumStr.length() > 0){
                        res.setBoxNumStr(boxNumStr.toString());
                    }
                }catch (Exception e){
                }
            }
        }
    	return ResponseData.success(res);
    }
    
    /**
     * 入库单商品托盘列表
     * 查询入库单商品托盘列表
     */
    @ResponseBody
    @RequestMapping("/detailedlist")
    public ResponseData detailedlist(HxStoragePutDetailedParam hxStoragePutDetailedParam) {
    	List<HxStoragePutDetailedResult> res = hxStoragePutDetailedService.restfinddetailedSumDetailedlist(hxStoragePutDetailedParam);
        return ResponseData.success(res);
    }

    /**
     * 质检
     */
    @ResponseBody
    @RequestMapping("/quality")
    public ResponseData quality(HxStoragePutDetailedParam hxStoragePutDetailedParam) {
		User user = userAop.getUser();
		HxStoragePutDetailed hxStoragePutDetailed = hxStoragePutDetailedService.getById(hxStoragePutDetailedParam.getId());
        HxBasicGoods byId = hxBasicGoodsService.getById(hxStoragePutDetailed.getGoodsId());
        BigDecimal nums = new BigDecimal(hxStoragePutDetailedParam.getRealNum());
        // 获取当前日期
        Date currentDate = new Date();

        // 假设生产日期在 hxStoragePutDetailed 里有一个方法 getProductionDate
        String detailedDateString = hxStoragePutDetailedParam.getDetailedDate();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date productionDate = null;

        try {
            productionDate = dateFormat.parse(detailedDateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // 计算生产日期与当前日期的差值
        long diffInMillies = Math.abs(currentDate.getTime() - productionDate.getTime());
        long diffInDays = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
        if (productionDate.after(currentDate)) {
            return ResponseData.error("超前质检：质检日期不能晚于当前日期");
        }
        // 检查生产日期是否超过3个月（约90天）
//        if (diffInDays > 180) {
//            return ResponseData.error("超期：生产日期已超过6个月");
//        }
		if(hxStoragePutDetailed.getPutState().equals("待质检")) {
			hxStoragePutDetailedParam.setPutState("待上架");
			hxStoragePutDetailedParam.setQualityUserName(user.getName());
			hxStoragePutDetailedParam.setQualityTime(new Date());
            hxStoragePutDetailedParam.setJibenRealNum(new BigDecimal(hxStoragePutDetailedParam.getRealNum()).multiply(new BigDecimal(hxStoragePutDetailed.getRate())).toString());

            hxStoragePutDetailedService.update(hxStoragePutDetailedParam);
		}
        return ResponseData.success();
    }

    /**
     * 撤销-质检
     */
    @ResponseBody
    @RequestMapping("/revoke")
    public ResponseData revoke(HxStoragePutDetailedParam hxStoragePutDetailedParam) {
		HxStoragePutDetailed hxStoragePutDetailed = hxStoragePutDetailedService.getById(hxStoragePutDetailedParam.getId());
		if(hxStoragePutDetailed.getPutState().equals("待上架")) {
			hxStoragePutDetailedParam.setRealNum("0");
            hxStoragePutDetailedParam.setJibenRealNum("0");
			hxStoragePutDetailedParam.setDetailedDate("");
			hxStoragePutDetailedParam.setPutState("待质检");
			hxStoragePutDetailedService.update(hxStoragePutDetailedParam);
		} else {
	        return ResponseData.error("已被上架领取或已上架");
		}
        return ResponseData.success();
    }

    /**
     * 全部质检
     */
    @ResponseBody
    @RequestMapping("/allquality")
    public ResponseData allquality(HxStoragePutDetailedParam hxStoragePutDetailedParam) {
		User user = userAop.getUser();

		hxStoragePutDetailedParam.setPutState("待上架");
		hxStoragePutDetailedParam.setQualityUserName(user.getName());
		hxStoragePutDetailedParam.setQualityTime(new Date());
        Date currentDate = new Date();

        // 假设生产日期在 hxStoragePutDetailed 里有一个方法 getProductionDate
        String detailedDateString = hxStoragePutDetailedParam.getDetailedDate();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date productionDate = null;

        try {
            productionDate = dateFormat.parse(detailedDateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // 计算生产日期与当前日期的差值
        long diffInMillies = Math.abs(currentDate.getTime() - productionDate.getTime());
        long diffInDays = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
        if (productionDate.after(currentDate)) {
            return ResponseData.error("超前质检：质检日期不能晚于当前日期");
        }
        // 检查生产日期是否超过3个月（约90天）
//        if (diffInDays > 180) {
//            return ResponseData.error("超期：生产日期已超过6个月");
//        }
        hxStoragePutDetailedService.allqualityupdateBySpec(hxStoragePutDetailedParam);
        return ResponseData.success();
    }

    /**
     * 规则属性修改
     */
    @ResponseBody
    @RequestMapping("/editGoods")
    public ResponseData editGoods(HxStoragePutDetailedParam hxStoragePutDetailedParam) {
		User user = userAop.getUser();
		ResponseData data = new ResponseData();
        synchronized (user.getUserId()){
    		data = hxStoragePutDetailedService.editGoods(user,hxStoragePutDetailedParam);
        }
		return data;
    }

    /**
     * 新增
     */
    @ResponseBody
    @RequestMapping("/add")
    public ResponseData add(HxStoragePutDetailedParam hxStoragePutDetailedParam) {
		User user = userAop.getUser();
		ResponseData data = new ResponseData();
        synchronized (user.getUserId()){
    		data = hxStoragePutDetailedService.addGoods(user,hxStoragePutDetailedParam);
        }
		return data;
    }

    /**
     * 删除
     */
    @ResponseBody
    @RequestMapping("/delete")
    public ResponseData delete(HxStoragePutDetailedParam hxStoragePutDetailedParam) {
        List <HxStoragePutDetailed> list = hxStoragePutDetailedService.lambdaQuery()
                .eq(HxStoragePutDetailed::getStorageNumber, hxStoragePutDetailedParam.getStorageNumber())
                .eq(HxStoragePutDetailed::getGoodsId, hxStoragePutDetailedParam.getGoodsId())
                .list();
        int count = list.size();
    	if(count == 1) {
    		return ResponseData.error("最后一托不可删除");
    	}
    	hxStoragePutDetailedService.delete(hxStoragePutDetailedParam);
		return ResponseData.success();
    }

    /**
     * 查询待领取 分页
     * @author zhucx
     * @Date 2023-08-14
     */
    @ResponseBody
    @RequestMapping("/appfindPagedailingqu")
    public LayuiPageInfo appfindPagedailingqu(HxStoragePutDetailedParam hxStoragePutDetailedParam,String condition ) {
		User user = userAop.getUser();
    	hxStoragePutDetailedParam.setPutState("待上架");
    	hxStoragePutDetailedParam.setDeptId(user.getDeptId());
    	hxStoragePutDetailedParam.setOperateId(user.getOperateId());
        return this.hxStoragePutDetailedService.findAppDailingquPageBySpec(hxStoragePutDetailedParam,condition);
    }


    /**
     * 查询待领取
     * @author zhucx
     * @Date 2023-08-14
     */
    @ResponseBody
    @RequestMapping("/appfindPagedailingquall")
    public List<HxStoragePutDetailedResult> appfindPagedailingquall(HxStoragePutDetailedParam hxStoragePutDetailedParam,String condition ) {
		User user = userAop.getUser();
    	hxStoragePutDetailedParam.setPutState("待上架");
    	hxStoragePutDetailedParam.setDeptId(user.getDeptId());
    	hxStoragePutDetailedParam.setOperateId(user.getOperateId());
        return this.hxStoragePutDetailedService.findAppDailingquBySpec(hxStoragePutDetailedParam,condition);
    }
    
    /**
     * 查询已领取
     */
    @ResponseBody
    @RequestMapping("/appfindlistyilingqu")
    public ResponseData appfindlistyilingqu(HxStoragePutDetailedParam hxStoragePutDetailedParam) {
		User user = userAop.getUser();
		hxStoragePutDetailedParam.setPutState("已领取");
		hxStoragePutDetailedParam.setReceiveUser(user.getAccount());
    	hxStoragePutDetailedParam.setDeptId(user.getDeptId());
    	hxStoragePutDetailedParam.setOperateId(user.getOperateId());
		List<HxStoragePutDetailedResult> list = hxStoragePutDetailedService.appfindlistyilingqu(hxStoragePutDetailedParam);
        return ResponseData.success(list);
    }

    /**
     * 领取任务
     */
    @ResponseBody
    @RequestMapping("/receive")
    public ResponseData receive(HxStoragePutDetailedParam hxStoragePutDetailedParam) {
		User user = userAop.getUser();
		if(user.getOperateId() != null) {
        	synchronized(user.getOperateId()) {
        		HxStoragePutDetailed hxStoragePutDetailed = hxStoragePutDetailedService.getById(hxStoragePutDetailedParam.getId());
        		if(hxStoragePutDetailed.getPutState().equals("待上架")) {
        			hxStoragePutDetailedParam.setPutState("已领取");
        			hxStoragePutDetailedParam.setReceiveUser(user.getAccount());
        			hxStoragePutDetailedParam.setReceiveUserName(user.getName());
        			hxStoragePutDetailedService.update(hxStoragePutDetailedParam);
        		} else {
                    return ResponseData.error("已被领取");
                }
        	}
        } else {
            return ResponseData.error("账号不支持上架");
        }
        return ResponseData.success();
    }
    
    @Autowired
    private UserService userService;

    /**
     * 撤销-领取
     */
    @ResponseBody
    @RequestMapping("/revokeReceive")
    public ResponseData revokeReceive(HxStoragePutDetailedParam hxStoragePutDetailedParam) {
		User user = userAop.getUser();
        List<Long> roleList = new ArrayList<Long>();
		String[] split = user.getRoleId().split(",");//以逗号分割
        for (String string2 : split) {
        	roleList.add(Long.parseLong(string2));
        }
        List<Menu> mlist = userService.getAppletsPermissionlist(roleList,"/rest/HxStoragePut/revokeReceive");
        if(mlist.size() == 0) {
            return ResponseData.error("权限异常");
        }
        
		HxStoragePutDetailed hxStoragePutDetailed = hxStoragePutDetailedService.getById(hxStoragePutDetailedParam.getId());
		if(hxStoragePutDetailed.getPutState().equals("已领取")) {
			hxStoragePutDetailedParam.setPutState("待上架");
            hxStoragePutDetailedParam.setRevokeName(user.getName());
			hxStoragePutDetailedService.update(hxStoragePutDetailedParam);
		}
        return ResponseData.success();
    }

    /**
     * 查询任务
     */
    @ResponseBody
    @RequestMapping("/detailed")
    public ResponseData detailed(HxStoragePutDetailedParam hxStoragePutDetailedParam) {
		User user = userAop.getUser();
		HxStoragePutDetailedResult res = hxStoragePutDetailedService.appPutfindBySpec(hxStoragePutDetailedParam);

		if(!res.getPutState().equals("已领取")||!res.getReceiveUser().equals(user.getAccount())) {
			return ResponseData.error("任务不存在或不属于你！");
		}
        res.setBoxNumStr("-");
        StringBuffer boxNumStr = new StringBuffer();
        if(ToolUtil.isNotEmpty(res.getGoodsId())){
            HxBasicGoods hxBasicGoods = this.hxBasicGoodsService.getById(res.getGoodsId());
            if(ToolUtil.isNotEmpty(hxBasicGoods) && ToolUtil.isNotEmpty(hxBasicGoods.getBoxSpecs())){
                try {
                    res.setBoxSpecs(hxBasicGoods.getBoxSpecs());
                    BigDecimal boxSpecs = new BigDecimal(hxBasicGoods.getBoxSpecs());
                    if(ToolUtil.isNotEmpty(res.getNum())){
                        BigDecimal zs = new BigDecimal(res.getNum()).divide(boxSpecs, 0, RoundingMode.DOWN);
                        if(zs.compareTo(BigDecimal.ZERO) > 0){
                            boxNumStr.append(zs).append("箱");
                        }
                        BigDecimal ys = new BigDecimal(res.getNum()).remainder(boxSpecs);
                        if(ys.compareTo(BigDecimal.ZERO) > 0){
                            boxNumStr.append(ys.setScale(0,BigDecimal.ROUND_UP)).append(hxBasicGoods.getJibenUnit());
                        }
                    }
                    if(boxNumStr.length() > 0){
                        res.setBoxNumStr(boxNumStr.toString());
                    }
                }catch (Exception e){
                }
            }
        }

        return ResponseData.success(res);
    }
    
    /**
     * 查询库存列表
     */
    @ResponseBody
    @RequestMapping("/storageStocklist")
    public ResponseData storageStocklist(HxStorageStockParam hxStorageStockParam) {
		List<HxStorageStockResult> list = hxStoragePutDetailedService.storageStocklist(hxStorageStockParam);
        return ResponseData.success(list);
    }

    /**
     * 上架
     */
    @ResponseBody
    @RequestMapping("/put")
    public ResponseData put(HxStoragePutDetailedParam hxStoragePutDetailedParam) {
		User user = userAop.getUser();
		ResponseData data = new ResponseData();
		data.setSuccess(true);
        if(ToolUtil.isEmpty(hxStoragePutDetailedParam.getPositionNumber())){
            return ResponseData.error("未获取到库位编号");
        }
		if(user.getOperateId() != null) {
	        synchronized (user.getOperateId()){
	    		HxStoragePutDetailed detailed = hxStoragePutDetailedService.getById(hxStoragePutDetailedParam.getId());//入库明细
	    		if(detailed.getPutState().equals("已领取")) {
	                hxStoragePutDetailedParam.setJibenRealNum(new BigDecimal(detailed.getRealNum()).multiply(new BigDecimal(detailed.getRate())).toString());
	
	                data = hxStoragePutDetailedService.put(user,detailed,hxStoragePutDetailedParam);
	    		} else {
	                return ResponseData.error("上架任务不存在或已上架");
	    		}
	        }
		} else {
            return ResponseData.error("账号不支持上架");
        }
		return data;
    }
    
    

}
